package cn.wolfcode.wolf2w.service.impl;

import cn.wolfcode.wolf2w.domain.Destination;
import cn.wolfcode.wolf2w.domain.Travel;
import cn.wolfcode.wolf2w.domain.UserInfo;
import cn.wolfcode.wolf2w.exception.LogicException;
import cn.wolfcode.wolf2w.query.TravelCondition;
import cn.wolfcode.wolf2w.query.TravelQuery;
import cn.wolfcode.wolf2w.repository.TravelRepository;
import cn.wolfcode.wolf2w.service.IDestinationService;
import cn.wolfcode.wolf2w.service.ITravelService;
import cn.wolfcode.wolf2w.service.IUserInfoService;
import cn.wolfcode.wolf2w.util.DBHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.List;
import java.util.Optional;

/**
 * 旅游日记服务接口实现
 */
@Service
//@Transactional  现在写不能事务, 需要讲完复制集才能使用事务
public class TravelServiceImpl implements ITravelService {

    @Autowired
    private TravelRepository repsitory;

    @Autowired
    private MongoTemplate template;
    @Autowired
    private IUserInfoService userInfoService;
    @Autowired
    private IDestinationService destinationService;


    @Override
    public void save(Travel travel) {
        travel.setId(null);
        repsitory.save(travel);
    }

    @Override
    public void update(Travel travel) {
        repsitory.save(travel);
    }

    @Override
    public void delete(String id) {
        repsitory.deleteById(id);
    }

    @Override
    public Travel get(String id) {
        Optional<Travel> op = repsitory.findById(id);
        Travel travel = null;
        if (op.isPresent()) {
            travel = op.get();
            travel.setAuthor(userInfoService.get(travel.getUserId()));
            travel.setDest(destinationService.get(travel.getDestId()));
        }

        return travel;
    }

    @Override
    public List<Travel> list() {
        return repsitory.findAll();
    }

    @Override
    public Page<Travel> query(TravelQuery qo) {
        Query query = new Query();
        if (StringUtils.hasLength(qo.getDestId())) {
            query.addCriteria(Criteria.where("destId").is(qo.getDestId()));
        }
        //获取旅游天数
        TravelCondition day = TravelCondition.DAY_MAP.get(qo.getDayType());
        if (day != null) {
            //拼接查询条件
            query.addCriteria(Criteria.where("day").gte(day.getMin()).lte(day.getMax()));
        }
        //获取人均消费
        TravelCondition pre = TravelCondition.PEREXPEND_MAP.get(qo.getPerExpendType());
        if (pre != null) {
            query.addCriteria(Criteria.where("perExpend").gte(pre.getMin()).lte(pre.getMax()));
        }
        Pageable pageable = null;

        if (qo.getOrderType() == TravelQuery.ORDER_NEW) {
            pageable = PageRequest.of(qo.getCurrentPage() - 1, qo.getPageSize(), Sort.Direction.DESC, "createTime");
        } else if (qo.getOrderType() == TravelQuery.ORDER_HOT) {
            pageable = PageRequest.of(qo.getCurrentPage() - 1, qo.getPageSize(), Sort.Direction.DESC, "viewnum");
        } else {
            pageable = PageRequest.of(qo.getCurrentPage() - 1, qo.getPageSize(), Sort.Direction.ASC, "_id");
        }
        Page<Travel> page = DBHelper.query(template, pageable, query, Travel.class, qo);
        //处理作者头像地址异常
        for (Travel travel : page) {
            travel.setAuthor(userInfoService.get(travel.getUserId()));
        }
        return page;
    }

    @Override
    //游记审核
    public void updateStateById(String id, int state) {
        //通过id获取当前游记
        Travel travel = this.get(id);
//        1、判断是否满足审核条件
        if (travel == null || travel.getState() != Travel.STATE_WAITING) {
            throw new LogicException("参数异常");
        }

//        2、审核通过之后要做什么:
//        3、游记状态改为审核通过/发布:
        if (state == Travel.STATE_RELEASE) {
            travel.setState(Travel.STATE_RELEASE);
//        4、游记发布时间为当前时间
            travel.setCreateTime(new Date());
//        5、游记最后修改时间
            travel.setLastUpdateTime(new Date());
//            6、记录审核信息:审核人审核时间审核意见.
        } else if (state == Travel.STATE_REJECT) {
            //        7、审核拒绝之后要做什么
//        8、游记状态改为审核拒绝
            travel.setState(Travel.STATE_REJECT);
            //          10、游记最后修改时间
            travel.setLastUpdateTime(new Date());
//        9、游记发布时间
            travel.setCreateTime(null);

        } else {
            throw new LogicException("参数异常");
        }
        this.update(travel);
    }

    @Override

    //游记点击量前三
    public List<Travel> querytravelsViewnumTop3ByDestId(String destId) {
       Pageable pageable= PageRequest.of(0,3, Sort.Direction.DESC,"viewnum");
        return repsitory.findTravelsByDestId(destId,pageable);
    }

    @Override
    public void saveOrUpdate(Travel travel) {
        //添加缺失信息补全
        //目的地
        String destId = travel.getDestId();
        Destination destination = destinationService.get(destId);
        travel.setDestName(destination.getName());
        //最后修改时间
       travel.setLastUpdateTime(new Date());
         //发布时间
        travel.setReleaseTime(null);

        if (StringUtils.hasLength(travel.getId())) {
            //update
            //编辑数据保留
            Travel travel1 = this.get(travel.getId());
            travel.setCreateTime(travel1.getCreateTime());
            travel.setFavornum(travel1.getFavornum());
            travel.setReplynum(travel1.getReplynum());
            travel.setSharenum(travel1.getSharenum());
            travel.setThumbsupnum(travel1.getThumbsupnum());
            travel.setViewnum(travel1.getViewnum());
            travel.setContent(travel1.getContent());
            this.update(travel);
        } else {
            //save
            travel.setCreateTime(new Date());
            this.save(travel);
        }
    }

    @Override
    public List<Travel> queryByDestName(String destName) {
        List<Travel> travels = repsitory.findByDestName(destName);
        for (Travel travel : travels) {
            travel.setAuthor(userInfoService.get(travel.getUserId()));
            travel.setDest(destinationService.get(travel.getDestId()));
        }
        return travels;
    }
    }

